import { Request, Response, NextFunction } from "express";
import { ResponseWrapper } from '../utils/ResponseWrapper';
import { HttpStatusCode, ErrorCode } from '../types/statusCodes';
import { logger } from '../config/logger'; // 导入日志配置

/**
 * 增强版 404 处理器
 * 提供更详细的错误信息和可能的解决方案建议
 */
export const notFoundHandler = (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  // 记录 404 请求（用于分析和监控）
  logger.error('404 Not Found:', {
    timestamp: new Date().toISOString(),
    method: req.method,
    path: req.path,
    ip: req.ip,
    userAgent: req.get('User-Agent')
  });

  // 构建错误详情
  const errorDetails = {
    path: req.path,
    method: req.method,
    timestamp: new Date().toISOString(),
    suggestedActions: [
      '检查请求的URL是否正确',
      '确认请求方法(GET, POST, PUT, DELETE)是否正确',
      '查看API文档确认可用端点'
    ],
    documentationUrl: '/api/docs' // 可以指向您的API文档地址
  };

  // 根据请求的Accept头部决定响应格式
  const accepts = req.get('Accept') || '';

  if (accepts.includes('text/html')) {
    // 如果是浏览器请求，可以返回HTML页面
    res.status(HttpStatusCode.NOT_FOUND).send(`
      <!DOCTYPE html>
      <html>
        <head>
          <title>404 - 资源未找到</title>
          <style>
            body { font-family: Arial, sans-serif; text-align: center; padding: 50px; }
            h1 { color: #d32f2f; }
            pre { background: #f5f5f5; padding: 15px; border-radius: 5px; text-align: left; }
          </style>
        </head>
        <body>
          <h1>404 - 资源未找到</h1>
          <p>请求的资源 <code>${req.method} ${req.path}</code> 不存在</p>
          <pre>${JSON.stringify(errorDetails, null, 2)}</pre>
        </body>
      </html>
    `);
  } else {
    // API请求返回JSON格式错误
    ResponseWrapper.error(
      res,
      `请求的资源 ${req.method} ${req.path} 不存在`,
      HttpStatusCode.NOT_FOUND,
      ErrorCode.RESOURCE_NOT_FOUND,
      errorDetails
    );
  }
};

/**
 * 简化的 404 处理器（基础版本）
 * 仅返回JSON格式的错误响应
 */
export const simpleNotFoundHandler = (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  ResponseWrapper.error(
    res,
    `请求的资源 ${req.method} ${req.path} 不存在`,
    HttpStatusCode.NOT_FOUND,
    ErrorCode.RESOURCE_NOT_FOUND,
    {
      path: req.path,
      method: req.method
    }
  );
};